package linear.sequential.impl;

import linear.sequential.SequentialList;

import java.util.Iterator;

/**
 * @author caasi
 * @since 2022-01-08 10:27:56
 */
public class SequentialListImpl<T> implements SequentialList<T> {
    
    //当前元素个数
    private int length;
    
    //数据元素
    private T[] elements;
    
    //容量
    private int capacity;
    
    public SequentialListImpl(){
        this(16);
    }
    
    //指定容量
    public SequentialListImpl(int capacity){
        this.elements = (T[]) new Object[capacity];
        this.length = 0;
        this.capacity = capacity;
    }
    
    @Override
    public void clear() {
        elements = (T[]) new Object[capacity];
        length = 0;
    }

    @Override
    public boolean isEmpty() {
        return length == 0;
    }

    @Override
    public int length() {
        return length;
    }

    @Override
    public T get(int i) {
        return elements[i];
    }

    @Override
    public void insert(int i, T t) {
        ensureCapacity();
        for (int j = length; j > i; j--) {
            elements[j] = elements[j - 1];
        }
        elements[i] = t;
        length ++;
    }

    @Override
    public void insert(T t) {
        ensureCapacity();
        elements[length++] = t;
    }
    
    public void ensureCapacity(){
        if(length == capacity) {
          int newLength = length << 1;
          T[] newElements = (T[]) new Object[newLength]; 
          System.arraycopy(elements, 0, newElements, 0, length);
          elements = newElements;
          capacity = newLength;
        } 
    }
    
    
    @Override
    public T remove(int i) {
        if(isEmpty()) throw new RuntimeException("线性表为空");
        T remove = elements[i];
        for(int j = i; j < length - 1; j++){
            elements[j] = elements[j + 1];
        }
        elements[length - 1] = null;
        length --;
        return remove;
    }

    @Override
    public int indexOf(T t) {
        for(int i = 0; i < length; i++){
            if(elements[i].equals(t)) return i;
        }
        return -1;
    }
    
    @Override
    public Iterator<T> iterator() {
        return new SequentialListIterator();
    }

    private class SequentialListIterator implements Iterator<T>{
        
        private int cursor;
        
        public SequentialListIterator(){
            cursor = 0;
        }
        
        @Override
        public boolean hasNext() {
            return cursor != length;
        }

        @Override
        public T next() {
            return elements[cursor++];
        }
    }
}
